<?php
Class module {
	
	public $name;
	public $action;
	public $format;
	
	private $attached;
	
	static function load(request $request, $cssclass = null) {
		$config = config::getInstance();
		if (!file_exists($modulefile = $config->site_root."/modules/$request->module.php")) {
			error::fatal("Module file '$modulefile' not found");
		}
		include_once $modulefile;
		if (!class_exists($classname = "module_$request->module")) {
			error::fatal("Module class '$classname' not found");
		}
		
		// add css/js
		document::getInstance()->addCSS("templates/".$request->module."/css/".$request->action.".css");
		document::getInstance()->addJS("templates/".$request->module."/js/".$request->action.".js");
		
		// execute action
		$ret = new $classname();
		$ret->name = $request->module;
		$ret->action = $request->action;
		$ret->format = $request->format;
		
		// container
		if ($cssclass) {
			echo "<div class='$cssclass'>";
		}
		
		if (method_exists($ret, $request->action) || method_exists($ret, "__call")) {
			$ret->{$request->action}();
		} else {
			error::warning("Module action '$request->action' is not available");
		}
		
		if ($cssclass) {
			echo "</div>";
		}
		
		return $ret;		
	}
	
	static function loadToPosition(request $request, $position, $cssclass = null) {
		ob_start();
		$ret = module::load($request, $cssclass);
		$doc = document::getInstance();
		$doc->contents[$position] = ob_get_contents();
		ob_end_clean();
		return $ret;
	}
	
	function attach($name, $value) {
		$this->attached[$name] = $value;
	}
	
	function output($template = null) {
		$this->{$this->format}($template);
	}
	
	function page($template = null) {
		$this->html($template);
	}
	
	function xhtml($template = null) {
		$this->html($template);
	}
	
	function box($template = null) {
		$this->html($template, "box");
	}
	
	function html($template = null, $format = "html") {
		if (empty($template)) { $template = $this->action; }
		$config = config::getInstance();
		if (!file_exists($templatefile = $config->site_root."/templates/$this->name/$template.$format.php")) {
			error::fatal("Template file $templatefile not found");
		}
		// extract vars
		if (!empty($this->attached)) {
			foreach ($this->attached as $key => $value) {
				$$key = $value;
			}
		}
		include $templatefile;		
	}
	
	function json() {
		echo "JSON output here...";
	}
	
	function xml() {
		echo "XML output here...";
	}
	
}
?>